﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Collections.Concurrent;
using System.Threading;
using System.IO;

namespace AspNetSimple
{
    public partial class frmMain3 : Form
    {
        public class Teacher
        {
            [MiniExcelLibs.Attributes.ExcelColumnName("个人地址")]
            public string Href { get; set; }
            [MiniExcelLibs.Attributes.ExcelColumnName("岗位")]
            public string Title { get; set; }
            [MiniExcelLibs.Attributes.ExcelColumnName("姓名")]
            public string Name { get; set; }
            [MiniExcelLibs.Attributes.ExcelColumnName("职称")]
            public string Post { get; set; }
            [MiniExcelLibs.Attributes.ExcelColumnName("个人介绍")]
            public string Introduce { get; set; }
            [MiniExcelLibs.Attributes.ExcelColumnName("研究方向")]
            public string Interest { get; set; }
            [MiniExcelLibs.Attributes.ExcelColumnName("个人成就")]
            public string Achievement { get; set; }
            [MiniExcelLibs.Attributes.ExcelColumnName("照片")]
            public string Photo { get; set; }
        }

        public frmMain3()
        {
            InitializeComponent();
            webBrowserHtml.DocumentCompleted += Navigated;
            webBrowserDetail.DocumentCompleted += DetailCompleted;

        }

        private void DetailCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            MyWebBrowser browser = (sender as MyWebBrowser);
            string url = browser.Url.ToString();
            string path = browser.Url.PathAndQuery;
            // Console.WriteLine("[Detail] Navigate: {0}", url);
            browser.Document.Window.Error += (sender1, e1) =>
            {
                e1.Handled = true;
            };
            string post = null;
            string title = null;
            string introduce = null;
            string interest = null;
            string photo = null;
            string achievement = null;
            var elementCollection = browser.Document.Body.GetElementsByTagName("div");
            //
            foreach (HtmlElement item in elementCollection)
            {
                string css = item.GetAttribute("className");
                if (css.Contains("Section0"))
                {
                    introduce = item.InnerText;
                }
            }

            var ele2 = browser.Document.Body.GetElementsByTagName("img");

            foreach (HtmlElement item in ele2)
            {
                string css = item.GetAttribute("className");

                if (css.Contains("img_vsb_content"))
                {
                    photo = item.GetAttribute("src");
                }
            }

            var teacher = teachers.Where(c => c.Href == url).FirstOrDefault();
            if (teacher != null)
            {
                Console.WriteLine("[{3}],{0},{1},{2},{4},{5},{6},{7}", url, teacher.Title, teacher.Post, teacher.Post, interest, introduce, achievement, photo);

                teacher.Achievement = achievement;
                teacher.Interest = interest;
                teacher.Introduce = introduce;
                teacher.Photo = photo;
                teacher.Title = post;
            }

            if (save)
            {
                string filename = @"C:\Users\reemoon\Desktop\" + DotNetExtensions.AspNet.Snowflake.Default.NextId() + ".xlsx";
                Console.WriteLine("Save 3 = " + filename);
                MiniExcelLibs.MiniExcel.SaveAs(filename, teachers);
            }
        }
        private Thread thread;
        ConcurrentQueue<Teacher> queue = new ConcurrentQueue<Teacher>();
        private bool save = false;
        private void TaskQueue()
        {
            thread = new Thread(new ThreadStart(() =>
              {
                  while (true)
                  {
                      Teacher item = null;
                      if (webBrowserDetail.InvokeRequired && queue.TryDequeue(out item))
                      {
                          webBrowserDetail.Invoke(new MethodInvoker(() =>
                          {
                              if (!webBrowserDetail.IsBusy)
                              {
                                  webBrowserDetail.Navigate(item.Href);
                                  webBrowserDetail.ScriptErrorsSuppressed = false;
                              }
                          }));
                          save = false;
                          Thread.Sleep(200);
                      }
                      else if (teachers.Any())
                      {
                          save = true; break;
                      }
                  }

              }));
            thread.Start();
        }
        private List<Teacher> teachers = new List<Teacher>();
        private void buttonNavigate_Click(object sender, EventArgs e)
        {
            string url = textBoxUrl.Text;
            if (!string.IsNullOrEmpty(url) && url.IndexOf("http") == 0)
            {
                teachers.Clear();
                Navigate(url);
            }
        }
        private void Employee(List<Teacher> employees)
        {
            foreach (var item in employees)
            {
                queue.Enqueue(item);

                Console.WriteLine("[{3}] - {0},{1},{2}", item.Href, item.Title, item.Name, item.Post);
            }

            teachers = employees;
            TaskQueue();
        }

        private void Navigate(string url)
        {
            webBrowserHtml.Navigate(url);
            webBrowserHtml.ScriptErrorsSuppressed = false;
        }

        private void Navigated(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            MyWebBrowser browser = (sender as MyWebBrowser);
            string url = browser.Url.ToString();
            string path = browser.Url.PathAndQuery;
            // Console.WriteLine("Navigate: {0}", url);
            ((SHDocVw.WebBrowser)browser.ActiveXInstance).Silent = true;
            browser.Document.Window.Error += (sender1, e1) =>
            {
                e1.Handled = true;
            };
            var elementCollection = browser.Document.Body.GetElementsByTagName("a");
            List<Teacher> employee = new List<Teacher>();
            foreach (HtmlElement item in elementCollection)
            {
                string title = item.InnerText;
                string href = item.GetAttribute("href");

                Regex regex = new Regex("/\\d{3,4}.htm$");
                if (!string.IsNullOrEmpty(title) && regex.IsMatch(href))
                {
                    employee.Add(new Teacher { Href = href, Name = title, Title = title });
                }

            }

            Employee(employee);

        }

        private void buttonBitmap_Click(object sender, EventArgs e)
        {
            WebBrowserConvert.Default.Completed += bitmap =>
            {
                pictureBoxBitmap.Image = bitmap;
            };
            WebBrowserConvert.Default.ToBitmap(new Uri(textBoxUrl.Text));
        }

        private void buttonDetail_Click(object sender, EventArgs e)
        {
            webBrowserDetail.Navigate(textBoxUrl.Text);
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (thread != null) { thread.Abort(); }
            }
            catch { }
        }
    }
}
